#include "Tkgles.h"
#include <basic.h>
#include <tk/tkernel.h>
#include <string.h>
#include <stdio.h>

EXPORT Display * initDisplay(){
	char device_name[8];
	ID screen_descriptor;
	ER	error_code;
	INT asiz;

	Display * d = Kmalloc(sizeof(Display));
	strcpy( device_name, "SCREEN" );
	screen_descriptor = tk_opn_dev( device_name, TD_UPDATE );
	if (screen_descriptor < E_OK){
		printf("Cannot open display\n");
	}
	error_code = tk_srea_dev( screen_descriptor, DN_SCRBMP, &(d->devbmp), sizeof(BMP), &asiz );
	if (error_code < E_OK || asiz != sizeof(BMP)) {
		printf ("Cannot read drawing space\n");
	}
	switch (d->devbmp.pixbits >> 8) { /* bit count per 1 pixel */
		case 8 :
			error_code = tk_swri_dev( screen_descriptor, DN_SCRCOLOR, (VP)colormap, sizeof(colormap), &asiz );
			if (error_code < E_OK || asiz != sizeof(colormap)){
				printf("Cannot update color map\n");
			}
			break;
    }
/*	int x,y;
	for (x = 0; x < 240; x++){
		for (y = 0; y < 320; y++){
			draw_buff(x,y,0x00);
		}
	}*/ 
	return d;
}
EXPORT void DrawPixel(GLint x, GLint y, GLint color){
	glDisplay->ScreenBuffer[x][y] = color;
}
EXPORT void flush_display(){
	int x,y;
	for (x = 0; x < 240; x++){
		for (y = 0; y < 320; y++){
			draw(x,y,glDisplay->ScreenBuffer[x][y],&(glDisplay->devbmp));
		}
	}
}
EXPORT void ClearScreenBuffer(){
    int x,y;
    for (x = 0; x < 240; x++){
        for(y = 0; y < 320; y++){
            glDisplay->ScreenBuffer[x][y] = 0x00FFFFFF;
        }
    }
}
